const cp = require('child_process')
const { resolve } = require('path')
const mongoose = require('mongoose')
const Movie = mongoose.model('movie')
const schedule = require('node-schedule')
const sendMail = require('./mailer')
const moment = require('moment')
const { destroy } = require('../controllers/vip')

const crawlMovie = async () => {
  const script = resolve(__dirname, '../crawler/movie')
  const child = cp.fork(script, [])
  let startTime = moment(new Date())
  let totalNum = 0
  let invoked = false

  child.on('error', err => {
    if (invoked) return
    invoked = true
    console.log(err)
  })

  child.on('exit', code => {
    if (invoked) return
    invoked = true
    let endTime = moment(new Date())
    let du = moment.duration(endTime - startTime, 'ms')
    let timeStr = `${du.get('hours')}时${du.get('minutes')}分${du.get('seconds')}秒`
    if (code === 0) {
      sendMail({
        to: [
          '956164483@qq.com',
          '807092862@qq.com'
        ],
        subject: '本次更新${totalNum}部，用时${timeStr}',
        html: `
        <a href="http://suo.im/4MFuiV">最新地址</a>
        `
      }).then(info => {
        console.log('->更新邮件已发送')
      }).catch(err => {
        console.log(err)
      })
    }
    destroy()
    console.log(`->本次更新${totalNum}部，用时${timeStr}`)
  })

  child.on('message', async data => {
    let result = data.result
    let count = 0
    for(let i = 0; i < result.length; i++) {
      let item = result[i]
      let movie = await Movie.findOne({
        m3u8Url: item.m3u8Url
      })
      if (!movie) {
        count++
        movie = new Movie(item)
        await movie.save()
      }
    }
    totalNum += count
    console.log(`->本次录入${count}部`)
  })
}

let rule = new schedule.RecurrenceRule()
rule.dayOfWeek = [0, new schedule.Range(1, 6)]
rule.hour = [6, 15]
rule.minute = [45]
rule.second = [0]

schedule.scheduleJob(rule, () => {
  crawlMovie()
})
